package cn.edu.jsu.zjj.aspect;

import cn.edu.jsu.zjj.annotation.Type;
import cn.edu.jsu.zjj.model.entity.OperLog;
import cn.edu.jsu.zjj.model.entity.User;
import cn.edu.jsu.zjj.service.OperLogService;
import cn.edu.jsu.zjj.service.UserService;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 请求响应日志 AOP
 *
 **/
@Aspect
@Component
@Slf4j
public class LogAspect {

    @Autowired
    UserService userService;

    @Autowired
    OperLogService operLogService;

    /**
     * 执行拦截
     */
    @Around("@annotation(cn.edu.jsu.zjj.annotation.Type)")
    public Object doInterceptor(ProceedingJoinPoint point) throws Throwable {
        // 计时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 获取请求路径
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 生成请求唯一 id
        String requestId = UUID.randomUUID().toString();
        String url = httpServletRequest.getRequestURI();
        // 获取请求参数
        Object[] args = point.getArgs();
        String reqParam = "[" + StringUtils.join(args, ", ") + "]";
        // 输出请求日志
        log.info("request start，id: {}, path: {}, ip: {}, params: {}", requestId, url,
                httpServletRequest.getRemoteHost(), reqParam);

        // 执行原方法
        Object result = point.proceed();
        // 输出响应日志
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        log.info("request end, id: {}, cost: {}ms", requestId, totalTimeMillis);
            // 获取操作人员
        User user = userService.getLoginUser();
        MethodSignature sign = (MethodSignature) point.getSignature();
        OperLog operLog = OperLog.builder()
                .operName(user.getName())
                .operTime(LocalDateTime.now())
                .costTime(totalTimeMillis)
                .remark(sign.getMethod().getAnnotation(Type.class).value())
                .roles(JSONUtil.toJsonStr(user.getRoles()))
                .status("0")
                .build();
        operLogService.save(operLog);
        return result;
    }
}
